interface AnythingLLMConfig {
    url: string;
    apiKey: string;
    selectedWorkspace?: {
        slug: string;
        name: string;
    };
}

interface Workspace {
    id: number;
    name: string;
    slug: string;
    createdAt: string;
    lastUpdatedAt: string;
}

interface AISettings {
    provider: 'deepseek' | 'anythingllm';
    anythingllm?: AnythingLLMConfig;
}

class AISettingsManager {
    private electron = require('electron');
    
    // DOM elements
    private providerOptions!: NodeListOf<HTMLElement>;
    private anythingllmConfig!: HTMLElement;
    private workspaceSection!: HTMLElement;
    private urlInput!: HTMLInputElement;
    private apiKeyInput!: HTMLInputElement;
    private testConnectionBtn!: HTMLButtonElement;
    private testConnectionText!: HTMLElement;
    private connectionStatus!: HTMLElement;
    private refreshWorkspacesBtn!: HTMLButtonElement;
    private refreshWorkspacesText!: HTMLElement;
    private workspaceList!: HTMLElement;
    private saveBtn!: HTMLButtonElement;
    private cancelBtn!: HTMLButtonElement;
    private voiceSettingsBtn!: HTMLButtonElement;
    
    // 窗口控制按钮
    private windowMinimizeBtn!: HTMLButtonElement;
    private windowMaximizeBtn!: HTMLButtonElement;
    private windowCloseBtn!: HTMLButtonElement;
    
    private currentSettings: AISettings = {
        provider: 'deepseek'
    };
    private workspaces: Workspace[] = [];
    private selectedWorkspace: Workspace | null = null;

    constructor() {
        this.initializeElements();
        this.setupEventListeners();
        this.loadSettings();
        console.log('AI设置管理器初始化完成');
    }

    private initializeElements(): void {
        this.providerOptions = document.querySelectorAll('.provider-option');
        this.anythingllmConfig = document.getElementById('anythingllmConfig') as HTMLElement;
        this.workspaceSection = document.getElementById('workspaceSection') as HTMLElement;
        this.urlInput = document.getElementById('anythingllmUrl') as HTMLInputElement;
        this.apiKeyInput = document.getElementById('anythingllmApiKey') as HTMLInputElement;
        this.testConnectionBtn = document.getElementById('testConnectionBtn') as HTMLButtonElement;
        this.testConnectionText = document.getElementById('testConnectionText') as HTMLElement;
        this.connectionStatus = document.getElementById('connectionStatus') as HTMLElement;
        this.refreshWorkspacesBtn = document.getElementById('refreshWorkspacesBtn') as HTMLButtonElement;
        this.refreshWorkspacesText = document.getElementById('refreshWorkspacesText') as HTMLElement;
        this.workspaceList = document.getElementById('workspaceList') as HTMLElement;
        this.saveBtn = document.getElementById('saveBtn') as HTMLButtonElement;
        this.cancelBtn = document.getElementById('cancelBtn') as HTMLButtonElement;
        this.voiceSettingsBtn = document.getElementById('voiceSettingsBtn') as HTMLButtonElement;
        
        // 窗口控制按钮
        this.windowMinimizeBtn = document.getElementById('windowMinimizeBtn') as HTMLButtonElement;
        this.windowMaximizeBtn = document.getElementById('windowMaximizeBtn') as HTMLButtonElement;
        this.windowCloseBtn = document.getElementById('windowCloseBtn') as HTMLButtonElement;
    }

    private setupEventListeners(): void {
        // 提供商选择
        this.providerOptions.forEach(option => {
            option.addEventListener('click', () => {
                const provider = option.dataset.provider as 'deepseek' | 'anythingllm';
                this.selectProvider(provider);
            });
        });

        // 测试连接
        this.testConnectionBtn.addEventListener('click', () => {
            this.testConnection();
        });

        // 刷新工作区
        this.refreshWorkspacesBtn.addEventListener('click', () => {
            this.refreshWorkspaces();
        });

        // 保存设置
        this.saveBtn.addEventListener('click', () => {
            this.saveSettings();
        });

        // 取消
        this.cancelBtn.addEventListener('click', () => {
            this.closeWindow();
        });

        // 移除语音识别设置
        // this.voiceSettingsBtn.addEventListener('click', () => {
        //     this.electron.ipcRenderer.send('show-doubao-settings');
        // });

        // 窗口控制按钮
        this.windowMinimizeBtn.addEventListener('click', () => {
            this.minimizeWindow();
        });

        this.windowMaximizeBtn.addEventListener('click', () => {
            this.toggleMaximizeWindow();
        });

        this.windowCloseBtn.addEventListener('click', () => {
            this.closeWindow();
        });

        // URL和API Key输入框变化时清除状态
        this.urlInput.addEventListener('input', () => {
            this.clearConnectionStatus();
        });

        this.apiKeyInput.addEventListener('input', () => {
            this.clearConnectionStatus();
        });

        // IPC事件监听
        this.setupIpcListeners();
    }

    private setupIpcListeners(): void {
        // 接收AnythingLLM测试连接结果
        this.electron.ipcRenderer.on('anythingllm-test-result', (event: any, result: any) => {
            this.handleTestResult(result);
        });

        // 接收工作区列表
        this.electron.ipcRenderer.on('anythingllm-workspaces', (event: any, result: any) => {
            this.handleWorkspacesResult(result);
        });

        // 接收设置保存结果
        this.electron.ipcRenderer.on('ai-settings-saved', (event: any, success: boolean) => {
            if (success) {
                this.closeWindow();
            } else {
                alert('设置保存失败，请重试');
            }
        });

        // 接收当前设置
        this.electron.ipcRenderer.on('current-ai-settings', (event: any, settings: AISettings) => {
            this.loadSettingsData(settings);
        });
    }

    private selectProvider(provider: 'deepseek' | 'anythingllm'): void {
        this.currentSettings.provider = provider;

        // 更新UI
        this.providerOptions.forEach(option => {
            const radio = option.querySelector('input[type="radio"]') as HTMLInputElement;
            if (option.dataset.provider === provider) {
                option.classList.add('active');
                radio.checked = true;
            } else {
                option.classList.remove('active');
                radio.checked = false;
            }
        });

        // 显示/隐藏AnythingLLM配置
        if (provider === 'anythingllm') {
            this.anythingllmConfig.classList.add('show');
        } else {
            this.anythingllmConfig.classList.remove('show');
            this.workspaceSection.classList.remove('show');
        }
    }

    private async testConnection(): Promise<void> {
        const url = this.urlInput.value.trim();
        const apiKey = this.apiKeyInput.value.trim();

        if (!url || !apiKey) {
            this.showConnectionStatus('请填写服务器地址和API密钥', 'error');
            return;
        }

        // 显示加载状态
        this.setTestButtonLoading(true);
        this.showConnectionStatus('正在测试连接...', 'pending');

        // 发送测试请求到主进程
        this.electron.ipcRenderer.send('test-anythingllm-connection', { url, apiKey });
    }

    private handleTestResult(result: any): void {
        this.setTestButtonLoading(false);

        if (result.success) {
            this.showConnectionStatus('连接成功！', 'success');
            // 自动获取工作区列表
            this.refreshWorkspaces();
        } else {
            this.showConnectionStatus(`连接失败: ${result.error}`, 'error');
            this.workspaceSection.classList.remove('show');
        }
    }

    private async refreshWorkspaces(): Promise<void> {
        const url = this.urlInput.value.trim();
        const apiKey = this.apiKeyInput.value.trim();

        if (!url || !apiKey) {
            alert('请先配置服务器地址和API密钥');
            return;
        }

        // 显示加载状态
        this.setRefreshButtonLoading(true);

        // 发送获取工作区请求
        this.electron.ipcRenderer.send('get-anythingllm-workspaces', { url, apiKey });
    }

    private handleWorkspacesResult(result: any): void {
        this.setRefreshButtonLoading(false);

        if (result.success) {
            this.workspaces = result.workspaces;
            this.renderWorkspaces();
            this.workspaceSection.classList.add('show');
        } else {
            alert(`获取工作区失败: ${result.error}`);
        }
    }

    private renderWorkspaces(): void {
        this.workspaceList.innerHTML = '';

        if (this.workspaces.length === 0) {
            const emptyItem = document.createElement('div');
            emptyItem.className = 'workspace-item';
            emptyItem.innerHTML = '<div>未找到工作区</div>';
            this.workspaceList.appendChild(emptyItem);
            return;
        }

        this.workspaces.forEach(workspace => {
            const item = document.createElement('div');
            item.className = 'workspace-item';
            if (this.selectedWorkspace?.slug === workspace.slug) {
                item.classList.add('selected');
            }

            item.innerHTML = `
                <div>
                    <div class="workspace-name">${this.escapeHtml(workspace.name)}</div>
                    <div class="workspace-slug">${this.escapeHtml(workspace.slug)}</div>
                </div>
            `;

            item.addEventListener('click', () => {
                this.selectWorkspace(workspace);
            });

            this.workspaceList.appendChild(item);
        });
    }

    private selectWorkspace(workspace: Workspace): void {
        this.selectedWorkspace = workspace;
        this.renderWorkspaces();
    }

    private showConnectionStatus(message: string, type: 'success' | 'error' | 'pending'): void {
        this.connectionStatus.textContent = message;
        this.connectionStatus.className = `status-indicator status-${type}`;
    }

    private clearConnectionStatus(): void {
        this.connectionStatus.textContent = '';
        this.connectionStatus.className = '';
        this.workspaceSection.classList.remove('show');
    }

    private setTestButtonLoading(loading: boolean): void {
        this.testConnectionBtn.disabled = loading;
        if (loading) {
            this.testConnectionText.innerHTML = '<span class="loading"></span>测试中...';
        } else {
            this.testConnectionText.textContent = '测试连接';
        }
    }

    private setRefreshButtonLoading(loading: boolean): void {
        this.refreshWorkspacesBtn.disabled = loading;
        if (loading) {
            this.refreshWorkspacesText.innerHTML = '<span class="loading"></span>获取中...';
        } else {
            this.refreshWorkspacesText.textContent = '刷新工作区列表';
        }
    }

    private loadSettings(): void {
        // 请求当前设置
        this.electron.ipcRenderer.send('get-current-ai-settings');
    }

    private loadSettingsData(settings: AISettings): void {
        this.currentSettings = settings;

        // 设置提供商
        this.selectProvider(settings.provider);

        // 加载AnythingLLM配置
        if (settings.anythingllm) {
            this.urlInput.value = settings.anythingllm.url || '';
            this.apiKeyInput.value = settings.anythingllm.apiKey || '';

            if (settings.anythingllm.selectedWorkspace) {
                this.selectedWorkspace = {
                    ...settings.anythingllm.selectedWorkspace,
                    id: 0, // 临时ID
                    createdAt: '',
                    lastUpdatedAt: ''
                };
            }
        }
    }

    private saveSettings(): void {
        // 构建设置对象
        const settings: AISettings = {
            provider: this.currentSettings.provider
        };

        if (settings.provider === 'anythingllm') {
            const url = this.urlInput.value.trim();
            const apiKey = this.apiKeyInput.value.trim();

            if (!url || !apiKey) {
                alert('请填写AnythingLLM服务器地址和API密钥');
                return;
            }

            if (!this.selectedWorkspace) {
                alert('请选择一个工作区');
                return;
            }

            settings.anythingllm = {
                url,
                apiKey,
                selectedWorkspace: {
                    slug: this.selectedWorkspace.slug,
                    name: this.selectedWorkspace.name
                }
            };
        }

        // 发送保存请求
        this.electron.ipcRenderer.send('save-ai-settings', settings);
    }

    private closeWindow(): void {
        this.electron.ipcRenderer.send('close-ai-settings');
    }

    private minimizeWindow(): void {
        this.electron.ipcRenderer.send('minimize-ai-settings');
    }

    private toggleMaximizeWindow(): void {
        this.electron.ipcRenderer.send('toggle-maximize-ai-settings');
    }

    private escapeHtml(text: string): string {
        const div = document.createElement('div');
        div.textContent = text;
        return div.innerHTML;
    }
}

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', () => {
    new AISettingsManager();
}); 